package com.lhfeiyu.action.back.base.auth;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.base.BasePage;
import com.lhfeiyu.po.AuctionInst;
import com.lhfeiyu.po.AuctionProfession;
import com.lhfeiyu.po.base.BaseAdmin;
import com.lhfeiyu.po.base.BaseApply;
import com.lhfeiyu.po.base.BaseDict;
import com.lhfeiyu.po.base.BaseForum;
import com.lhfeiyu.po.base.BaseForumMember;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseNotice;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.AuctionInstService;
import com.lhfeiyu.service.AuctionProfessionService;
import com.lhfeiyu.service.base.BaseApplyService;
import com.lhfeiyu.service.base.BaseDictService;
import com.lhfeiyu.service.base.BaseForumMemberService;
import com.lhfeiyu.service.base.BaseForumService;
import com.lhfeiyu.service.base.BaseNoticeService;
import com.lhfeiyu.service.base.BaseUserService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Pagination;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.RequestUtil;

/**
 * <strong> 描&nbsp;&nbsp;&nbsp;&nbsp;述：</strong> 基础库-控制层-后台：申请 Apply <p>
 * <strong> 作&nbsp;&nbsp;&nbsp;&nbsp;者：</strong> 虞荣华 <p>
 * <strong> 编写时间：</strong> 2016年4月12日12:06:03 <p>
 * <strong> 公&nbsp;&nbsp;&nbsp;&nbsp;司：</strong> 成都蓝海飞鱼科技有限公司 http://lhfeiyu.com <p>
 * <strong> 版&nbsp;&nbsp;&nbsp;&nbsp;本：</strong> 2.0 <p>
 * <strong> 备&nbsp;&nbsp;&nbsp;&nbsp;注：</strong> 包路径：com.lhfeiyu.action.back.auth.BackApplyAction <p>
 */
@Controller
@RequestMapping(value="/back")
public class BackApplyAction {
	
	@Autowired
	private BaseApplyService applyService;
	@Autowired
	private BaseUserService userService;
	@Autowired
	private BaseDictService dictService;
	@Autowired
	private BaseForumService forumService;
	@Autowired
	private AuctionInstService auctionInstService;
	@Autowired
	private BaseForumMemberService forumMemberService;
	@Autowired
	private BaseNoticeService noticeService;
	private static Logger logger = Logger.getLogger("R");
	
	/**
	 * 加载后台申请页面
	 * @param modelMap
	 * @return ModelAndView
	 */
	@RequestMapping(value="/page/apply")
	public ModelAndView apply(ModelMap modelMap){
		String path = BasePage.back_apply;
		try{
			
		}catch(Exception e){
			path = BasePage.back_error;
			Result.catchError(e, logger, this.getClass().getName()+"/back/page/apply", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	/**
	 * 加载申请列表数据
	 * @param request
	 * @return JSONObject(rows,total,status,success)
	 */
	@ResponseBody
	@RequestMapping(value = "/getApplyList",method=RequestMethod.POST)
	public JSONObject getApplyList(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = Pagination.getOrderByAndPage(RequestUtil.getRequestParam(request), request);
			map.put("parentCodeNotNull", 1);//不查跟节点
			applyService.getApplyList(json, map);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/getApplyList", json);
		}
		return json;
	}
	
	@ResponseBody
	@RequestMapping(value="/getApplyTypeList")
	public JSONArray getApplyTypeList(HttpServletRequest request) {
		JSONArray array = new JSONArray();
		try {
			Map<String, Object> map = ActionUtil.getAllParam(request);
			map.put("parentCode", "apply_type");
			List<BaseDict> dict = dictService.selectListByCondition(map);
			for(BaseDict u : dict){
				JSONObject json = new JSONObject();
				json.put("id",u.getId());
				json.put("name",u.getCodeName());
				array.add(json);
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_获取申请类型出现异常_", array);
		}
		return array;
	}
	/**
	 * 论坛认证
	 * @param apply ModelAttribute
	 * @param request
	 * @return JSONObject
	 */
	@ResponseBody
	@RequestMapping(value = "/addOrUpdateForumApply", method = RequestMethod.POST)
	public JSONObject addOrUpdateForumApply(@ModelAttribute BaseApply apply,HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			Date d = new Date();
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			String username = admin.getUsername();
			BaseNotice notice=new BaseNotice();
			notice.setSendTime(d);
			notice.setSenderId(admin.getId());
			notice.setSenderName(username);
			notice.setReceiverId(apply.getUserId());
			notice.setTitle("申请通知");
			notice.setContent(apply.getReplyDesc());
			noticeService.insert(notice);
			int mainStatus= apply.getMainStatus();
			if(mainStatus==2){
			BaseForum forum = new BaseForum();
			BaseApply apply2= applyService.selectByPrimaryKey(apply.getId());
			forum.setLogo(apply2.getFile1());
			forum.setName(apply2.getAttr1());
			forum.setOwnerId(apply2.getUserId());
			forum.setCreatedBy(username);
			forum.setModeratorId(apply2.getUserId());
			forum.setSubModeratorId(apply2.getUserId());
			forum.setCreatedAt(new Date());
			forumService.insertSelective(forum);
			BaseForumMember baseForumMember = new BaseForumMember();
			baseForumMember.setForumId(forum.getId());
			baseForumMember.setUserId(apply.getUserId());
			forumMemberService.insertSelective(baseForumMember);
			}
			applyService.addUpdateApply(json, apply, username);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/addUpdateApply", json);
		}
		return Result.success(json);
	}
	/**
	 * 机构认证
	 * @param apply ModelAttribute
	 * @param request
	 * @return JSONObject
	 */
	@ResponseBody
	@RequestMapping(value = "/addOrUpdateProfessionApply", method = RequestMethod.POST)
	public JSONObject addOrUpdateProfessionApply(@ModelAttribute BaseApply apply,HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			Date d = new Date();
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			String username = admin.getUsername();
			BaseNotice notice=new BaseNotice();
			notice.setSendTime(d);
			notice.setSenderId(admin.getId());
			notice.setSenderName(username);
			notice.setReceiverId(apply.getUserId());
			notice.setTitle("申请通知");
			notice.setContent(apply.getReplyDesc());
			noticeService.insert(notice);
			int mainStatus= apply.getMainStatus();
			if(mainStatus==2){
			AuctionInst auctionInst = new AuctionInst();
			BaseApply apply2= applyService.selectByPrimaryKey(apply.getId());
			auctionInst.setName(apply2.getAttr1());
			auctionInst.setDescription(apply2.getAttr2());
			auctionInst.setTel(apply2.getAttr3());
			auctionInst.setUserId(apply2.getUserId());
			auctionInst.setPicPaths(apply2.getFile1());
			auctionInst.setCreatedBy(username);
			auctionInst.setCreatedAt(new Date());
			auctionInst.setSerial(CommonGenerator.getSerialByDate("ai"));
			auctionInstService.insertSelective(auctionInst);
			}
			applyService.addUpdateApply(json, apply, username);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/addUpdateApply", json);
		}
		return Result.success(json);
	}
	//企业认证
	@ResponseBody
	@RequestMapping(value = "/addOrUpdateSafetyApply", method = RequestMethod.POST)
	public JSONObject addOrUpdateSafetyApply(@ModelAttribute BaseApply apply,HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			Date d = new Date();
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			String username = admin.getUsername();
			BaseNotice notice=new BaseNotice();
			notice.setSendTime(d);
			notice.setSenderId(admin.getId());
			notice.setSenderName(username);
			notice.setReceiverId(apply.getUserId());
			notice.setTitle("申请通知");
			notice.setContent(apply.getReplyDesc());
			noticeService.insert(notice);
			int mainStatus= apply.getMainStatus();
			if(mainStatus==2){
			BaseUser user = new BaseUser();
			BaseApply apply2= applyService.selectByPrimaryKey(apply.getId());
			user.setId(apply.getUserId());
			user.setLinkCode(apply2.getAttr1());
			user.setLinkCode2(apply2.getAttr2());
			user.setLinkCode3(apply2.getAttr3());
			user.setLinkCode4(apply2.getFile2());
			user.setUpdatedBy(username);
			user.setUpdatedAt(new Date());
			user.setIsEnterpriseAuth(-1);
			userService.updateByPrimaryKeySelective(user);
			}
			applyService.updateByPrimaryKeySelective(apply);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/addUpdateApply", json);
		}
		return Result.success(json);
	}

	/**
	 * 逻辑删除申请数据
	 * @param request
	 * @param ids ID串
	 * @return JSONObject
	 */
	@ResponseBody
	@RequestMapping(value = "/updateApplyDelete", method=RequestMethod.POST)
	public JSONObject updateApplyDelete(HttpServletRequest request, @RequestParam String ids) {
		JSONObject json = new JSONObject();
		try {
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			applyService.updateDeletedNowByIds(ids, admin.getUsername());
			Result.success(json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/updateApplyDelete", json);
		}
		return json;
	}
	
	/**
	 * 物理删除申请
	 * @param request
	 * @param ids ID串
	 * @return JSONObject
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteApplyThorough",method=RequestMethod.POST)
	public JSONObject deleteApplyThorough(HttpServletRequest request, @RequestParam String ids) {
		JSONObject json = new JSONObject();
		try {
			//Admin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			applyService.deleteByIds(ids);
			Result.success(json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/deleteApplyThorough", json);
		}
		return json;
	}
	
	/**
	 * 恢复申请（去除逻辑删除状态）
	 * @param request
	 * @param ids ID串
	 * @return JSONObject
	 */
	@ResponseBody
	@RequestMapping(value = "/updateApplyRecover", method=RequestMethod.POST)
	public JSONObject updateApplyRecover(HttpServletRequest request, @RequestParam String ids) {
		JSONObject json = new JSONObject();
		try {
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			applyService.updateDeletedNullByIds(ids, admin.getUsername());
			Result.success(json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/back/updateApplyRecover", json);
		}
		return json;
	}
	

}

